package com.example.educationalsystem.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.educationalsystem.common.util.DateFormates;
import com.example.educationalsystem.common.util.ExcelListener;
import com.example.educationalsystem.common.util.ResponseJson;
import com.example.educationalsystem.common.util.UploadFileService;
import com.example.educationalsystem.entity.File;
import com.example.educationalsystem.entity.Student;
import com.example.educationalsystem.entity.User;
import com.example.educationalsystem.service.IFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import static com.baomidou.mybatisplus.core.toolkit.StringPool.NULL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zpc
 * @since 2022-12-26
 */

@Api(tags="文件管理")
@RestController
@RequestMapping("/file")
public class FileController {
        @Autowired
        private IFileService iFileService;
        @Autowired
        private UploadFileService uploadFileService;

        @GetMapping("/getAllfile")
        @ApiOperation(value = "获取所有附件", notes = "获取所有附件存储的链接")
        @ApiParam(NULL)
        @ResponseBody
        public ResponseJson getAllFile() {
            ResponseJson ResponseJson = new ResponseJson();
            List<File> files = iFileService.getBaseMapper().selectList(Wrappers.lambdaQuery());
            if (files != null) {
                ResponseJson.setStatus(200);
                ResponseJson.setMsg("查询成功！");
                ResponseJson.setData(files);
                return ResponseJson;
            } else {
                ResponseJson.setStatus(404);
                ResponseJson.setMsg("查询为空，无连接！");
                return ResponseJson;
            }
        }
    @ApiOperation(value = "分页查询文件信息", notes = "分页查询文件信息，需要提供页数和一页大小（即一页几条数据）")
    @GetMapping(value = "/filePage")
    @ResponseBody
    public ResponseJson filePage(@RequestParam long current, @RequestParam long size) {
        ResponseJson responseJson = new ResponseJson();
        Page<File> filePage = new Page<>(current, size);
        Page<File> studentPages =iFileService.getBaseMapper().selectPage(filePage, null);
        responseJson.setMsg("分页查询成功");
        responseJson.setData(studentPages);
        responseJson.setStatus(200);
        return responseJson;
    }
    @ApiOperation(value = "导出文件信息",notes = "导出文件信息")
    @ResponseBody
    @GetMapping("Download")
    public void myDownload(HttpServletResponse response, @RequestParam String tableName) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename="+ new String(tableName.getBytes(StandardCharsets.UTF_8),"ISO8859-1")+".xls");
//        System.out.println(iStudentServic.toString());
        EasyExcel.write(response.getOutputStream(), File.class).sheet(tableName).doWrite(iFileService.getBaseMapper().selectList(Wrappers.lambdaQuery()));
    }
    @ApiOperation(value = "批量删除学生信息",notes = "根据学生编号，删除多条学生信息")
    @DeleteMapping("/deleteFiles")
    @ResponseBody
    public  ResponseJson deleteFiles( @ApiParam(name = "Ids", value = "文件IDs", required = true) @RequestParam String Ids)
    {
        ResponseJson responseJson=new ResponseJson();
        String[] idArr = Ids.split(",");
        List<String> idList = Arrays.asList(idArr);
        boolean result=iFileService.removeByIds(idList);
        System.out.println(result);
        if(result)
        {
//            responseJson.setData(courseOne);
            responseJson.setMsg("批量删除成功！");
            responseJson.setStatus(200);
        }
        else
        {
            responseJson.setMsg("批量删除失败");
            responseJson.setStatus(400);
        }
        return responseJson;

    }
    @ApiOperation(value = "导入文件信息",notes = "导入文件信息")
    @ResponseBody
    @PostMapping("Import")
    public ResponseJson myImport(MultipartFile file) {
        ResponseJson responseJson=new ResponseJson();
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();

            EasyExcelFactory.read(inputStream, File.class, listener).headRowNumber(1).build().readAll();
            //获取数据
            List<Object> list = listener.getDatas();
            if (list.size() > 1) {
                for (int i = 0; i < list.size(); i++) {
                    File file1 = (File) list.get(i);
                    //使用mybatis-plus添加到数据库
                    iFileService.save(file1);
                }
            }
            responseJson.setStatus(200);
            responseJson.setMsg("导入成功！");
        } catch (Exception e) {
            responseJson.setStatus(400);
            responseJson.setMsg("导入失败！");
            e.printStackTrace();
        }

        return responseJson;
    }
        @ApiOperation(value = "存储文件", notes = "增加一条附件记录，附件ID不用填写，必须填写userID")
        @PostMapping("/insertFile")
        @ResponseBody
        public ResponseJson insertFile(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "fileTag") String fileTag, @RequestParam(value = "userName") String userName) throws IOException {
            ResponseJson ResponseJson = new ResponseJson();
            File files = new File();
            files.setUserName(userName);
            files.setId(0);
            files.setFileTag(fileTag);
            /**
             * @Param : url
             * @Description: 上传文件返回访问文件路径
             */
            String url = uploadFileService.uploads(file,fileTag);
            System.out.println(url);
            files.setFileUrl(url);
            Boolean result = iFileService.save(files);
            QueryWrapper<File> queryWrapper=new QueryWrapper<>();
            File res = iFileService.getBaseMapper().selectOne(queryWrapper.eq("file_url",files.getFileUrl()));
            if (result) {
                ResponseJson.setMsg("增加成功！");
                ResponseJson.setStatus(200);
                ResponseJson.setData(res);
                return ResponseJson;
            } else {
                ResponseJson.setStatus(400);
                ResponseJson.setMsg("增加失败！");
                return ResponseJson;
            }
        }


        @ApiOperation(value = "删除附件", notes = "根据链接标题，删除一条附件")
        @DeleteMapping("/deleteFile")
        @ResponseBody
        public ResponseJson deleteFile(@RequestParam(value = "ID") Integer ID) {
            ResponseJson ResponseJson = new ResponseJson();
            QueryWrapper<File> queryWrapper = new QueryWrapper<>();
            File FileOne = iFileService.getBaseMapper().selectOne(queryWrapper.eq("id",ID));
            if (FileOne != null) {
                int result = iFileService.getBaseMapper().deleteById(FileOne.getId());
                System.out.println(result);
                if (result == 1) {
                    ResponseJson.setData(FileOne);
                    ResponseJson.setMsg("删除成功！");
                    ResponseJson.setStatus(200);
                } else {
                    ResponseJson.setMsg("删除失败");
                    ResponseJson.setStatus(400);
                }

            } else {
                ResponseJson.setStatus(404);
                ResponseJson.setMsg("该附件不存在！");
            }
            return ResponseJson;

        }
        
        @ApiOperation(value = "更新附件信息", notes = "更新附件信息，必须填写附件ID")
        @PutMapping("/update")
        @ResponseBody
        public ResponseJson updateFile(@RequestBody File resquestFile) {
            ResponseJson ResponseJson = new ResponseJson();
            QueryWrapper<File> queryWrapper = new QueryWrapper<>();
            File FileOne = iFileService.getBaseMapper().selectOne(queryWrapper.eq("id", resquestFile.getId()));
            if (FileOne != null) {
                int result = iFileService.getBaseMapper().updateById(resquestFile);
                if (result == 1) {
                    ResponseJson.setMsg("更新成功！");
                    ResponseJson.setStatus(200);
                    ResponseJson.setData(resquestFile);
                } else {
                    ResponseJson.setMsg("更新失败！");
                    ResponseJson.setStatus(400);
                }

            } else {
                ResponseJson.setMsg("链接不存在");
                ResponseJson.setStatus(404);
            }
            return ResponseJson;
        }
}


